// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const { id, action } = event

  if (!id) {
    return {
      success: false,
      message: '文章ID不能为空'
    }
  }

  try {
    // 获取文章信息
    const article = await db.collection('articles').doc(id).get()
    if (!article.data) {
      return {
        success: false,
        message: '文章不存在'
      }
    }

    // 根据action执行相应操作
    if (action === 'add') {
      // 检查是否已收藏
      const exist = await db.collection('collections')
        .where({
          openid,
          articleId: id
        })
        .count()

      if (exist.total > 0) {
        return {
          success: false,
          message: '已经收藏过了'
        }
      }

      // 添加收藏
      await db.collection('collections').add({
        data: {
          openid,
          articleId: id,
          article: article.data,
          createTime: db.serverDate()
        }
      })

      return {
        success: true,
        message: '收藏成功'
      }

    } else if (action === 'remove') {
      // 删除收藏
      const result = await db.collection('collections')
        .where({
          openid,
          articleId: id
        })
        .remove()

      if (result.stats.removed > 0) {
        return {
          success: true,
          message: '取消收藏成功'
        }
      } else {
        return {
          success: false,
          message: '收藏记录不存在'
        }
      }

    } else {
      return {
        success: false,
        message: '无效的操作类型'
      }
    }

  } catch (err) {
    console.error('收藏操作失败:', err)
    return {
      success: false,
      message: '操作失败',
      error: err
    }
  }
}